package com.hpli.trigger.job;


import cn.bugstack.middleware.db.router.strategy.IDBRouterStrategy;
import com.hpli.domain.task.model.entity.TaskEntity;
import com.hpli.domain.task.service.ITaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author: 汀
 * @CreateTime: 2025-04-16
 * @Description: 发送MQ消息任务队列
 * @Version: 1.0
 */

@Slf4j
@Component
public class SendMessageTaskJob {

    @Resource
    private ITaskService taskService;

    @Resource
    private ThreadPoolExecutor executor;

    @Resource
    private IDBRouterStrategy dbRouter;


    @Scheduled(cron = "0/5 * * * * ?")
    public void exec_db01() {
        try {
            dbRouter.setDBKey(1);
            dbRouter.setTBKey(0);

            // 查询未发生的任务
            List<TaskEntity> taskEntities = taskService.queryNoSendMessageTaskList();
            if (taskEntities.isEmpty()) return;
            // 发送MQ消息
            for (TaskEntity task : taskEntities) {

                    try {
                        taskService.sendMessage(task);
                        taskService.updateTaskSendMessageCompleted(task.getUserId(), task.getMessageId());
                    } catch (Exception e) {
                        log.error("定时任务，发送MQ消息失败 userId={}, messageId={}", task.getUserId(), task.getMessageId());
                        taskService.updateTaskSendMessageFailed(task.getUserId(), task.getMessageId());
                    }

            }
        } catch (Exception e) {
            log.error("定时任务，扫描MQ任务表发送消息失败", e);
        } finally {
            dbRouter.clear();
        }
    }

    @Scheduled(cron = "0/5 * * * * ?")
    public void exec_db02() {
        try {
            dbRouter.setDBKey(2);
            dbRouter.setTBKey(0);

            // 查询未发生的任务
            List<TaskEntity> taskEntities = taskService.queryNoSendMessageTaskList();
            if (taskEntities.isEmpty()) return;
            // 发送MQ消息
            for (TaskEntity task : taskEntities) {
                    try {
                        taskService.sendMessage(task);
                        taskService.updateTaskSendMessageCompleted(task.getUserId(), task.getMessageId());
                    } catch (Exception e) {
                        log.error("定时任务，发送MQ消息失败 userId={}, messageId={}", task.getUserId(), task.getMessageId());
                        taskService.updateTaskSendMessageFailed(task.getUserId(), task.getMessageId());
                    }
            }
        } catch (Exception e) {
            log.error("定时任务，扫描MQ任务表发送消息失败", e);
        } finally {
            dbRouter.clear();
        }
    }
}
